package com.mocoop.plugin.camera;

import java.io.File;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.DisplayMetrics;

import com.mocoop.commom.MyConstants;
import com.mocoop.commom.PhotoUtils;
import com.mocoop.plugin.MocoopPlugin;

public class MyCamera extends MocoopPlugin {

	private String imgPath;
	private CallbackContext callbackContext;

	@Override
	public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {

		imgPath = MyConstants.getPath(getActivity(), getUserID()) + System.currentTimeMillis() + ".jpeg";
		this.callbackContext = callbackContext;
		File vFile = new File(imgPath);

		if (!vFile.exists())

		{

			File vDirPath = vFile.getParentFile(); // new
													// File(vFile.getParent());

			vDirPath.mkdirs();

		}

		Uri uri = Uri.fromFile(vFile);

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//

		try {
			cordova.startActivityForResult((CordovaPlugin) this, intent, 34);
		} catch (Exception e) {
			callbackContext.error(e.getMessage());
		}

		return true;
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {

		if (resultCode == Activity.RESULT_OK) {
			DisplayMetrics dm = new DisplayMetrics();
			getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);

			Bitmap bm = PhotoUtils.decodeOriginImage(imgPath, dm.widthPixels,
					dm.heightPixels);
			int degree = 0;
			try {
				degree = PhotoUtils.getBitmapDegree(imgPath);
			} catch (Exception e) {

			}
			if (degree != 0) {
				bm = PhotoUtils.rotateBitmapByDegree(bm, degree);
			}
			PhotoUtils.saveBitmapToFile(imgPath, bm);
			if (callbackContext != null)
				callbackContext.success("file://" + imgPath);
		}
	}
}
